/*
	This file is part of the JKTest
    Copyright (C) 2008 Royce Y. Feng <ryfeng@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License version 3
    as published by the Free Software Foundation. You may not use, modify
    or distribute this program under any other version of the
    GNU Affero General Public License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package JKPanels;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.util.ArrayList;

import jktest.JKMainPanel;
import jktest.JKMainGui;
import jktest.JKButton;
import handlers.JKSoftwareTestHandler;
import java.util.HashMap;

/**
 * 
 * Panel Class containing all elements of the Software Test
 * 
 * @author Royce Feng
 */
public class SoftwarePanel extends JKMainPanel {
    
    private class SoftwareInfo {

        public JKButton getButton() {
            return button;
        }

        public String getExeLocation() {
            return exeLocation;
        }

        public JLabel getlLocation() {
            return lLocation;
        }

        public JLabel getlName() {
            return lName;
        }

        public String getLocation() {
            return location;
        }

        public String getName() {
            return name;
        }
        private String name;
        private String location;
        private String exeLocation;
        private JLabel lName;
        private JLabel lLocation;
        private JKButton button;
        public SoftwareInfo(String name, String location, String exeLocation, JLabel lName, JLabel lLocation, JKButton button) {
            this.name = name;
            this.location = location;
            this.exeLocation = exeLocation;
            this.lName = lName;
            this.lLocation = lLocation;
            this.button = button;
        }
    }

    private PassFailPanel passFail;
    private JKSoftwareTestHandler handle;

    //Panels for labels
    private JScrollPane mainLabelPane;
    
    // HashMap for data storage
    private HashMap<String, SoftwareInfo> softwareMap = new HashMap<String, SoftwareInfo>();
    
    /**
     * 
     * Main Constructor for SoftwarePanel.
     * 
     * @param _parent The Parent Class (for communication)
     */
    public SoftwarePanel ( JKMainGui _parent ) {
        super(_parent);
        JKButton button = new JKButton(this,"Run Software");
        button.setPreferredSize(new Dimension(200,25));
        this.add( button );
        //handle = new JKSoftwareTestHandler(keys);
        ArrayList<String[]> softwares = loadSoftwareFromCSV();
        handle = new JKSoftwareTestHandler(softwares);
        passFail = new PassFailPanel(this);
        passFail.setPreferredSize(new Dimension(500,25));
        this.add(passFail);
    }

    /**
     *
     * Helper Function. This loads the software names and folder names from the
     * CSV file (should be located in the current working directory)
     *
     */
    private ArrayList<String[]> loadSoftwareFromCSV() {
        try {
            File f = new File("SoftwareFolders.csv");
            BufferedReader br = new BufferedReader(new FileReader(f));
            ArrayList<String[]> softwareList = new ArrayList<String[]>();
            String line;
            while ( ( line = br.readLine() ) != null ) {
                if ( !line.startsWith("//") ) { // Using // as comment denoters
                    String[] data = line.split(",");
                    if (data.length >= 2) {
                        softwareList.add(data);
                    }
                }
            }
            
            JPanel mainLabelPanel = new JPanel(new GridLayout(0,3));
            for ( int i = 0; i < softwareList.size(); i++ ) {
                String[] software = softwareList.get(i);
                // Create Labels and buttons
                JLabel softwareLabel = new JLabel(software[0]);
                JLabel softwareResultLabel = new JLabel("Not Detected");
                mainLabelPanel.add(softwareLabel);
                mainLabelPanel.add(softwareResultLabel);
                if (software.length > 2) {
                    JKButton softwareButton = new JKButton(this, software[0]);
                    softwareMap.put(software[0], new SoftwareInfo(
                            software[0],
                            software[1],
                            software[2],
                            softwareLabel,
                            softwareResultLabel,
                            softwareButton));
                    mainLabelPanel.add(softwareButton);
                } else {
                    softwareMap.put(software[0], new SoftwareInfo(
                            software[0],
                            software[1],
                            null,
                            softwareLabel,
                            softwareResultLabel,
                            null));
                    mainLabelPanel.add(new JLabel());
                }
            }
            mainLabelPanel.setBorder(new EmptyBorder(5,5,5,5));
            mainLabelPane = new JScrollPane( mainLabelPanel );
            mainLabelPane.setPreferredSize(new Dimension(600,200));
            this.add(mainLabelPane);
            
            br.close();
            return softwareList;
        } catch ( Exception e )  {
            JOptionPane.showMessageDialog(null, "Software not correctly loaded from file. Please restart JKTest", "Error", JOptionPane.ERROR_MESSAGE);
            return new ArrayList<String[]>();
        }
    }

    /**
     * 
     * Returns the name of the panel
     * 
     * @return The name of the panel
     */
    @Override
    public String getName() {
        return "Software";
    }
    
    /**
     * 
     * Handles button clicks. Pass/fail gets sent to parent while the test is run
     * when the test button is clicked.
     * 
     * @param source Button source (usually the button text)
     */
    public void ButtonClicked( String source ) {
        if ( source.equals("Pass") ) {
            getThisParent().valChanged(this.getName(), true);
            getThisParent().incPanel();
        } else if ( source.equals("Fail") ) {
            getThisParent().valChanged(this.getName(), false);
            getThisParent().incPanel();
        } else if ( source.equals("Run Software") ) {
            for ( String key : softwareMap.keySet() ) {
                SoftwareInfo sInfo = softwareMap.get(key);
                File f = new File(sInfo.getLocation());
                if (f.exists()) {
                    handle.setHash(sInfo.getName(), true);
                    sInfo.getlLocation().setText("Detected");
                }
            }
            getThisParent().valChanged(this.getName(), handle.getResult());
        } else {
            SoftwareInfo sInfo = softwareMap.get(source);
            if (sInfo != null) {
                sInfo.getExeLocation();
                try {
                    Runtime.getRuntime().exec(sInfo.getExeLocation());
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Could not start "+sInfo.getExeLocation(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
    
}
